﻿const TextToSVG = require('text-to-svg')
// 生成
const production = function({SVG, obj, options}) {
	let svg = '', maxX = 0, width = 0, height = 0;
	obj.arrList.forEach((item, i)=> {
		let path= SVG.getPath(item,options)
		let box = SVG.getMetrics(item,options)
		if (obj.underline) {
			path += `<line x1="${box.x}" x2="${box.width + box.x}" y1="${box.height}" y2="${box.height}" stroke-width="2"></line>`
		}
		//console.log(box)
		maxX < Math.abs(box.x) ? maxX = Math.abs(box.x) : maxX;
		let g = `<g transform='translate(${maxX},${(obj.size + obj.line * obj.size) * i})'>`
		g += path + '</g>'
		svg += g
		width = width < box.width ? width = box.width : width;
		height += box.height

	})
	return {svg, width, height}
}

function text(obj){
	return new Promise((resolve, reject) => {
		router.post('/textToPath/pro', (req, res) => {
			let obj = req.body || '';
			console.log(obj)
			if(obj == '') return res.send('传输为空')
			obj.align = 'top ' + obj.align
			let	options = { // 文字属性设置
					fontSize: obj.size, 
					anchor: obj.align,
					letterSpacing: obj.spacing,
					attributes: {
						transform: obj.itailic == 1 ? 'translate(10, 0) skewX(-15)' : '',
						'stroke-width': obj.bold,
						'stroke-linecap': 'round',
						'stroke-linejoin': 'round',
					}
				};
			let	SVG = TextToSVG.loadSync('./font/' + obj.family + '.ttf');// 字体设置
			let result = production({SVG, obj, options})
			res.send(result)
			
		})
	})
}

	

function setWS() {
	const webSocket = require('ws')
	var test = new webSocket.Server({port: 8888});
	test.on('connection', ws => {
		ws.send('ok')
		ws.on('message',data => {
			data = JSON.parse(data)
			text(data)
			.then(res => ws.send(res))
			ws.send('sdfsd')
			// test.clients.forEach(function (client) {
			// 	client.send('链接成功！');
			// });
		})
	})
}
module.exports = setWS